package com.forum.service.impl;

import com.forum.common.model.entity.Favorite;

import com.forum.mapper.FavoriteMapper;
import com.forum.mapper.PostMapper;
import com.forum.model.entity.Post;
import com.forum.model.vo.PostVO;
import com.forum.service.FavoriteService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏服务实现类
 */
@Service
@RequiredArgsConstructor
public class FavoriteServiceImpl implements FavoriteService {
    
    private final FavoriteMapper favoriteMapper;
    private final PostMapper postMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean favorite(Long userId, Long postId) {
        // 查询是否已收藏
        Favorite favorite = favoriteMapper.findByUserIdAndPostId(userId, postId);
        
        if (favorite != null) {
            // 已收藏，取消收藏
            favoriteMapper.deleteByUserIdAndPostId(userId, postId);
            return false;
        } else {
            // 未收藏，添加收藏
            favorite = new Favorite();
            favorite.setUserId(userId);
            favorite.setPostId(postId);
            favorite.setCreatedAt(LocalDateTime.now());
            favoriteMapper.insert(favorite);
            return true;
        }
    }
    
    @Override
    public boolean hasFavorited(Long userId, Long postId) {
        return favoriteMapper.existsByUserIdAndPostId(userId, postId) > 0;
    }
    
    @Override
    public int getFavoriteCount(Long postId) {
        return favoriteMapper.countByPostId(postId);
    }
    
    @Override
    public List<PostVO> getUserFavorites(Long userId) {
        // 获取用户收藏的帖子ID列表
        List<Long> postIds = favoriteMapper.selectPostIdsByUserId(userId);
        if (postIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 根据帖子ID列表获取帖子详情
        List<Post> posts = postMapper.selectByIds(postIds);
        return posts.stream()
                .map(post -> {
                    PostVO postVO = new PostVO();
                    BeanUtils.copyProperties(post, postVO);
                    return postVO;
                })
                .collect(Collectors.toList());
    }
} 